package org.web.ssm.controller.wechatController;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.web.ssm.dto.ResultModel;
import org.web.ssm.exception.OrderException;
import org.web.ssm.exception.UserException;
import org.web.ssm.model.OrderDetail;
import org.web.ssm.model.User;
import org.web.ssm.model.queryVo.BaseQuery;
import org.web.ssm.service.IOrderService;
import org.web.ssm.utils.JsonUtil;

import java.util.Date;

/**
 * Created by LUOLIANG on 2016/6/13.
 */
@RestController
@RequestMapping("/weOrder")
@SessionAttributes("currUser")
public class WeOrderController {
    private Logger logger = LogManager.getLogger(WeOrderController.class);
    @Autowired
    private IOrderService orderService;

    @RequestMapping(value = "/initorder", method = RequestMethod.POST)
    public String initOrder(OrderDetail orderDetail, @ModelAttribute("currUser") User user) {
        logger.info("接收到的参数:" + orderDetail.toString());
        System.out.println(user);
        orderDetail.setCreatetime(new Date());
        orderDetail.setUser(user);
        try {
            orderService.insertOrder(orderDetail);
            return JSON.toJSONString(new ResultModel<OrderDetail>("保存成功", true));
        } catch (OrderException e) {
            logger.error("订单保存错误：" + e.getMessage());
            return JSON.toJSONString(new ResultModel<User>(e.getMessage(), false));
        }
    }

    @RequestMapping(value = "/orderlist", method = RequestMethod.GET)
    public String orderlist(@ModelAttribute("currUser") User user, @RequestParam("type") String type) {
        System.out.println("查询方式：" + type);

        return JsonUtil.toJson("yyyy-MM-dd", new ResultModel<OrderDetail>(orderService.getAllOrderByUser(user.getUserid(), type), true));
    }

    @RequestMapping(value = "/orderlistByUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel<BaseQuery<OrderDetail>> orderlistByUser(int pageSize, int pageCurrent, int userId) {
        ResultModel<BaseQuery<OrderDetail>> resultModel = new ResultModel<BaseQuery<OrderDetail>>();
        BaseQuery<OrderDetail> result = null;
        try {
            result = orderService.orderlistByUser(pageSize, pageCurrent, userId);
            resultModel.setModel(result);

        } catch (UserException e) {
            logger.error("用户退出操作失败：" + e.getMessage());

        }
        return resultModel;
    }

    @RequestMapping(value = "/StatisticsData", method = RequestMethod.GET)
    public String StatisticsData(@ModelAttribute("currUser") User user) {

        return JsonUtil.toJson(orderService.getStatisData(user.getUserid()));
    }
}
